package baseLog

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

type Logger struct {
	*zap.SugaredLogger
	Loglevel zap.AtomicLevel
}

var (
	DefaultLogger      *Logger
	defaultLogPath     = "./log_record"
	defaultLogFileName = "default.log"
)

func init() {
	os.MkdirAll(defaultLogPath, os.ModePerm)
	defaultFile, _ := os.OpenFile(defaultLogPath+"/"+defaultLogFileName, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0777)
	DefaultLogger = NewLogger(defaultFile)
}

func NewLogger(ws zapcore.WriteSyncer) *Logger {
	lvl := zap.NewAtomicLevelAt(zap.DebugLevel)
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "ts",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
	return &Logger{
		SugaredLogger: zap.New(zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.Lock(ws), lvl)).WithOptions(zap.AddCaller(), zap.AddCallerSkip(1)).Sugar(),
		Loglevel:      lvl,
	}
}

type LoggerInterface interface {
	Debugf(format string, v ...interface{})
}

func Debugf(format string, v ...interface{}) {
	DefaultLogger.Debugf(format, v...)
}

func Debugw(msg string, keysAndValues ...interface{}) {
	DefaultLogger.Debugw(msg, keysAndValues...)
}

func Infof(format string, v ...interface{}) {
	DefaultLogger.Infof(format, v...)
}

func Infow(msg string, keysAndValues ...interface{}) {
	DefaultLogger.Infow(msg, keysAndValues...)
}

func Warnf(format string, v ...interface{}) {
	DefaultLogger.Warnf(format, v...)
}

func Errorf(format string, v ...interface{}) {
	DefaultLogger.Errorf(format, v...)
}

func Panicf(format string, v ...interface{}) {
	DefaultLogger.Panicf(format, v...)
}

func Fatalf(format string, v ...interface{}) {
	DefaultLogger.Fatalf(format, v...)
}
